package actions;

import gui.GUIWindow;

import java.awt.Cursor;
import java.awt.event.ActionEvent;

import javax.swing.JButton;
import javax.swing.JOptionPane;

import parameters.RlmServerParameters;
import server.RLM_Server;
import upnp.UPnpManager;
import application.Application;

@SuppressWarnings("serial")
public class StartAction extends SysTrayAbstractAction {

	public StartAction(GUIWindow owner) {
		setActionOwner(owner);
		
//		putValue(ACCELERATOR_KEY, KeyStroke.getKeyStroke(KeyEvent.VK_F7, 0));
//		putValue(SMALL_ICON, ImageCreator.createImageIcon(AboutAction.class, "images/start.png"));
		putValue(NAME, "Start");
		putValue(SHORT_DESCRIPTION, "Start");
		
		setActionItem();
	}
	
	
	public void actionPerformed(ActionEvent e) {
	
		getActionOwner().setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
		
		getActionOwner().getActionManager().setStartedRights();

		if ( !RlmServerParameters.isLan() ) {
			// zbog discavery timeout-a
			try {
				Thread.sleep(4000);
			} catch (InterruptedException ie) {
				// TODO Auto-generated catch block
				ie.printStackTrace();
			}
			
			String nicToConnect = RlmServerParameters.getNetworkInterfaceToConnect();
			boolean forwardFlag = UPnpManager.addTcpForward("RLM_Server", RlmServerParameters.getServerPort(), RlmServerParameters.getServerPort(), nicToConnect);
			
			if ( forwardFlag == false ) {
				String msg = String.format("UPnp forward to port %d failed. Please forward the port specified manually !", RlmServerParameters.getServerPort());
				JOptionPane.showMessageDialog(null, msg, "Warning!", JOptionPane.WARNING_MESSAGE);
//				exitRLMApplication();
			}
		}
		
		RLM_Server rlmServerProcess = new RLM_Server(getActionOwner().getApplication());
		rlmServerProcess.start();
		
		try {
			Application.startSemaphore.acquire();
		}
		catch (InterruptedException ie) {
			ie.printStackTrace();
		}
		
		if ( rlmServerProcess.isStarted() == false ) {
			JOptionPane.showMessageDialog(getActionOwner(), "Server starting error!", "Error", JOptionPane.ERROR_MESSAGE);
			JButton button = new JButton( getActionOwner().getActionManager().getStopAction() );
			button.doClick();
		}
		
		getActionOwner().setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR));
	}
	
}
